package com.bdcom.autotest.telnet;

import com.bdcom.autotest.config.ClientStartRun;
import com.bdcom.autotest.telnet.constant.TelnetConstant;
import com.bdcom.autotest.telnet.model.Result;
import com.bdcom.autotest.telnet.util.TelnetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TelnetTunnel implements TelnetConstant {
    private static final Logger logger = LoggerFactory.getLogger(ClientStartRun.class);
    private TelnetClientForCOM telnetClient;
    private TelnetCommunication communication;
    //ip地址
    private String ip;

    //端口
    private int port;

    //telnet 用户名
    private String user;

    //telnet 密码
    private String password;

    //enable 密码
    private String enablePassword;
    //是否Monitor模式
    private boolean isMonitor=false;

    public TelnetTunnel(String ip, int port, String user, String password, String enablePassword, boolean isMonitor) throws Exception {
        this.ip = ip;
        this.port = port;
        this.user = user;
        this.password = password;
        this.enablePassword = enablePassword;
        this.isMonitor = isMonitor;
        this.telnetClient=new TelnetClientForCOM(ip,port);
    }
    public TelnetClientForCOM getTelnetClient() {
        return telnetClient;
    }

    public void setTelnetClient(TelnetClientForCOM telnetClient) {
        this.telnetClient = telnetClient;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEnablePassword() {
        return enablePassword;
    }

    public void setEnablePassword(String enablePassword) {
        this.enablePassword = enablePassword;
    }

    public boolean isMonitor() {
        return isMonitor;
    }

    public void setMonitor(boolean monitor) {
        isMonitor = monitor;
    }

    public Result startTunnel(){
        communication=new TelnetCommunication();
        Result loginResult=new Result();
        try {
            loginResult= communication.login(user, password, telnetClient, isMonitor);
            return loginResult;
        }catch (Exception e){
            String error="Start Telnet Tunnel error["+e.toString()+"]";
            logger.error(error);
            loginResult.setFailedReason(error);
            loginResult.setStatus(false);
            return loginResult;

        }

    }

    public void closeTunnel(){
        try {
            telnetClient.disConnect();
        } catch (Exception e) {
            logger.error("Close Telnet Tunnel error["+e.toString()+"]");
        }
    }


    public Result setIPMask(String ip,String mask){
        //ip add 192.168.0.1 255.255.255.0
        Result result=new Result();
        StringBuilder builder=new StringBuilder();
        builder.append("ip add ").append(ip).append(" ").append(mask);
        String cmd=builder.toString();

        String retStr = null;
        try {
            retStr = telnetClient.sendCommand(cmd, 500L);
        } catch (Exception e) {
            String errorInfo="Set ip["+ip+"]mask["+mask+"]error["+e.toString()+"]";
            logger.error(errorInfo);
            result.setStatus(false);
            result.setFailedReason(errorInfo);
            return result;
        }
        if(retStr.endsWith(MONITOR_FLAG)){
            result.setStatus(true);
        }else{
            result.setStatus(false);
            result.setFailedReason(retStr);
        }

        return result;

    }
    //通用升级
    public Result upgradeGen(String srcFile,String dstFile,String tftpIP){
        //copy tftp:/工单号/BD_2228P_2.2.0D_76153_08036_2020.bin flash:Switch.bin 192.168.0.1
        Result result=new Result();
        StringBuilder builder=new StringBuilder();
        builder.append("copy tftp:").append(srcFile).append(" flash:").append(dstFile).append(" ").append(tftpIP);
        String cmd=builder.toString();
        try {
            Result enableResult = communication.enableOper(telnetClient, enablePassword,isMonitor);
            if(enableResult.getStatus()){
                //升级
                String retStr="";
                if (isMonitor){
                    retStr=communication.sendCommandWithRetryForMonitorUpgrade(telnetClient,EXEC_UPGRADE_MASTER_TIME,EXEC_UPGRADE_MASTER_RETRY_TIME,cmd,upgradeEndFlagsForMonitor);
                }else{
                    retStr=communication.sendCommandWithRetry(telnetClient,EXEC_UPGRADE_MASTER_TIME,EXEC_UPGRADE_MASTER_RETRY_TIME,cmd,upgradeEndFlags);
                }

                result= TelnetUtil.executeStatus(retStr,cmd);
                return result;

            }else{
                return enableResult;
            }
        } catch (Exception e) {
            String error="upgrade srcFile["+srcFile+"]dstFile["+dstFile+"] tftpIP["+tftpIP+"]error["+e.toString()+"]";
            result.setStatus(false);
            result.setFailedReason(error);
            logger.error(error);
            return result;
        }finally {
            if(!isMonitor){
                //非monitor模式下恢复telnet连接的COM口的初始状态
                try {
                    telnetClient.sendCommand("exit",200L);
                    telnetClient.sendCommand("exit",200L);
                } catch (Exception e) {
                    logger.error("exit error!"+e.toString());
                }

            }
        }


    }
     //eprom升级
    public Result upgradeForEPROM(String srcFile,String tftpIP){
        //copy tftp:G20008045482.bin rom 192.168.0.100
        //Update bootrom is dangerous,do you want to continue(y/n)?y
        StringBuilder builder=new StringBuilder();
        Result result=new Result();
        builder.append("copy tftp:").append(srcFile).append(" rom ").append(tftpIP);
        String cmd=builder.toString();
        try {
            //升级
            String retStr = telnetClient.sendCommand(cmd, 500L);
            if(retStr.contains("y/n")) {
                retStr = communication.sendCommandWithRetryForMonitorUpgrade(telnetClient, EXEC_UPGRADE_MASTER_TIME, EXEC_UPGRADE_MASTER_RETRY_TIME, "y", upgradeEndFlagsForMonitor);
                result=TelnetUtil.executeStatus(retStr,cmd);
                return result;
            }else{
                result.setStatus(false);
                result.setFailedReason("execute eprom,can't obtain select y/n");
                return result;
            }
        }catch (Exception e){
            String error="upgrade Eprom srcFile["+srcFile+"]tftpIP["+tftpIP+"]error["+e.toString()+"]";
            result.setStatus(false);
            result.setFailedReason(error);
            logger.error(error);
            return result;
        }


    }

    //默认配置文件升级
    public Result upgradeForDefaultConfig(String srcFile,String tftpIP){
        //先输入sh filesys-backdoor
        //再拷贝文件copy tftp:/工单号/default-config flash:default-config 192.168.0.1
        //dir确认default-config已存在
        //再输入sh filesys-backdoor
        StringBuilder builder=new StringBuilder();
        builder.append("copy tftp:").append(srcFile).append(" flash:").append("default-config").append(" ").append(tftpIP);
        String cmd= builder.toString();

        Result result=new Result();
        try {
            //1.升级前先执行（sh filesys-backdoor）
            String retStr=telnetClient.sendCommand("sh filesys-backdoor",1000L);
            if(retStr.contains("filesys backdoor is ON")){
                //开启，准备下一步升级
            }else if(retStr.contains("filesys backdoor is OFF")){
                //关闭，需要开启
                retStr=telnetClient.sendCommand("sh filesys-backdoor",1000L);
                if(retStr.contains("filesys backdoor is ON")){

                }else{
                    //开启失败
                    result.setStatus(false);
                    result.setFailedReason("Open filesys backdoor failed["+retStr+"]");
                    return result;
                }
            }else{
                result.setStatus(false);
                result.setFailedReason("filesys backdoor status["+retStr+"]");
                return result;
            }

            //2.升级
            retStr="";
            if (isMonitor){
                retStr=communication.sendCommandWithRetryForMonitorUpgrade(telnetClient,EXEC_UPGRADE_MASTER_TIME,EXEC_UPGRADE_MASTER_RETRY_TIME,cmd,upgradeEndFlagsForMonitor);
            }else{
                retStr=communication.sendCommandWithRetry(telnetClient,EXEC_UPGRADE_MASTER_TIME,EXEC_UPGRADE_MASTER_RETRY_TIME,cmd,upgradeEndFlags);
            }

            result=TelnetUtil.executeStatus(retStr,cmd);
            if(result.getStatus()){
                //3.升级后，dir确认default-config已存在 再执行afterCMD（sh filesys-backdoor）
                retStr=telnetClient.sendCommand("dir",3000L);
                if(retStr.contains("default-config")){
                    retStr=telnetClient.sendCommand("sh filesys-backdoor",1000L);
                    if(retStr.contains("filesys backdoor is OFF")){
                        //关闭成功
                        result.setStatus(true);
                        return result;
                    }else{
                        //关闭失败
                        result.setStatus(false);
                        result.setFailedReason("Close filesys backdoor failed!");
                        return result;
                    }

                }else{
                    result.setStatus(false);
                    result.setFailedReason("dir not find default-config");
                    return result;
                }


            }else{
                return result;
            }
        }catch (Exception e){
            String error="upgradeDefaultConfig srcFile["+srcFile+"]tftpIP["+tftpIP+"]error["+e.toString()+"]";
            result.setStatus(false);
            result.setFailedReason(error);
            logger.error(error);
            return result;
        }




    }


}
